package com.greate.community.controller.advice;

import com.greate.community.entity.User;
import com.greate.community.util.CommunityUtil;
import com.greate.community.util.HostHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 处理服务端异常（500）
 */
@ControllerAdvice(annotations = Controller.class) // 扫描带有 @Controller 的组件
public class ExceptionAdvice {
    @Autowired
    private HostHolder hostHolder;
    private static final Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public void argNotVaildhandleException(MethodArgumentNotValidException  e,HttpServletRequest request, HttpServletResponse response){
        String defaultMessage = e.getBindingResult().getFieldError().getDefaultMessage();
        System.out.println(defaultMessage+1);
    }

            //当前端传入的参数无效时 valid 输出异常  使用此方法会导致错误 被springsecurity拦截 原因未知
    @ExceptionHandler({BindException.class})
    public void argNotVaildhandleException2(BindException  e, HttpServletResponse response) throws IOException {
        String defaultMessage = e.getBindingResult().getFieldError().getDefaultMessage();
        logger.error("服务器发生异常：" + defaultMessage);
        //异常会导致postHandle 停止 不会存入用户信息
        User user = hostHolder.getUser();
//        if (user != null && modelAndView != null) {
//            modelAndView.addObject("loginUser", user);
//        }
        //返回异常信息
        response.setContentType("application/plain;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(CommunityUtil.getJSONString(400, defaultMessage));
    }
    @ExceptionHandler({Exception.class})
    public void handleException(Exception e,  HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.error("服务器发生异常：" + e.getMessage());
        for (StackTraceElement element : e.getStackTrace()) {
            logger.error(element.toString());
        }
        // 区分异步请求和普通请求
        String xRequestedWith = request.getHeader("x-requested-with");
        if ("XMLHttpRequest".equals(xRequestedWith)) {
            // 异步请求（希望返回的是 JSON 数据）
            response.setContentType("application/plain;charset=utf-8");
            PrintWriter writer = response.getWriter();

            writer.write(CommunityUtil.getJSONString(1, "服务器异常"));
        }
        else {
            // 普通请求（希望返回的是一个网页）
            response.sendRedirect(request.getContextPath() + "/error");
        }
    }

}
